import type { Request, ResponseToolkit } from "@hapi/hapi";
import Bcrypt from "bcryptjs";
import Hapi from "@hapi/hapi";
import Boom from "@hapi/boom";
import { User } from "../../model/index";

let route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  path: "/editPwd",
  method: "post",
  handler: async (r: Request, h: ResponseToolkit) => {
    try {
      const { account, oldPassword, newPassword } = r.payload as any;
      const user: any = await User.findOne({ account });
      console.log(user, "dd");
      if (user) {
        // const hashedPassword = await Bcrypt.hash(oldPassword, 10);
        // console.log(hashedPassword, user.password);
        const isValid = Bcrypt.compareSync(oldPassword, user.password);
        if (!isValid) {
          console.log("dd");
          throw Boom.badRequest("老密码错误");
        }
        const hashedPassword = await Bcrypt.hash(newPassword, 10);
        await User.updateOne(
          { _id: user._id },
          {
            password: hashedPassword,
          }
        );

        return {
          data: true,
          code: 200,
          message: "修改密码成功",
        };
      } else {
        return h
          .response({
            error: { message: "用户或者密码错误", code: 404 },
          })
          .code(400);
      }
    } catch (error) {
      return error;
    }
  },
  options: {
    payload: {
      parse: true, // 解析请求体
      allow: "application/json", // 允许JSON格式的请求体
    },
    auth: false,
    tags: ["api"],
  },
};
export default route;
